import * as base from "./base.js";
import instance from './request.js';
import { $, $$ } from './base.js';

window.addEventListener('load', function () {

    //跳转到发布房源页面
    if (localStorage.getItem('identity') == 2) {
        $('.add_fangyuan').style.display = 'block';
        $('.order_page_t_r').style.display = 'block';
    }

    base.navbox();
    base.avatarimg();


    $('.order_page_t_l span').innerHTML = window.localStorage.getItem('username');

    let orderarr;

    //退房arr
    let outarr = [];
    //正在住宿arr
    let livingarr = [];
    //尚未开始的订单arr
    let notarr = [];


    orderall();
    function orderall() {

        instance.get('/order/user', {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {

            orderarr = response.data.data;
            console.log(orderarr);


            if (orderarr != null) {
                $('.order_all').innerHTML = orderarr.length;
                $('.order_all1').innerHTML = orderarr.length;


                async function fetchData() {
                    let num1 = 0;
                    let num2 = 0;
                    let num3 = 0;
                    let num4 = 0;
                    let num5 = 0;

                    for (const [index, value] of orderarr.entries()) {
                        const detailResponse = await instance.get(`/home/detail/${value.homeId}`, {
                            headers: {
                                'Authorization': window.localStorage.getItem('token'),
                                'Content-Type': 'application/json',
                            }
                        });
                        const detailarr = detailResponse.data.data;

                        let str = `<div class="order_thing" data-order="${value.isReview}" data-orderid="${value.orderId}">
                        <div>订单 <span>${index + 1}</span> </div>
                        <div>
                          <table>
                            <thead>
                              <tr>
                                <th>房源信息</th>
                                <th></th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr>
                                <td>标题</td>
                                <td>${detailarr.title}</td>
                              </tr>
                              <tr>
                                <td>介绍</td>
                                <td>${detailarr.introduce}</td>
                              </tr>
                              <tr>
                                <td>最大入住人数</td>
                                <td>${detailarr.tenant}</td>
                              </tr>
                              <tr>
                                <td>价格</td>
                                <td>${detailarr.price}</td>
                              </tr>
                              <tr>
                                <td>评分</td>
                                <td>${detailarr.star}</td>
                              </tr>
                              <tr>
                                <td>房源类型</td>
                                <td>${detailarr.houseType.name}</td>
                              </tr>
                            </tbody>
                          </table>
                          <table>
                            <thead>
                              <tr>
                                <th>订单信息</th>
                                <th></th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr>
                                <td>开始时间</td>
                                <td>${value.startTime}</td>
                              </tr>
                              <tr>
                                <td>结束时间</td>
                                <td>${value.endTime}</td>
                              </tr>
                              <tr>
                                <td>订单号</td>
                                <td>${value.orderId}</td>
                              </tr>
                            </tbody>
                          </table>
                          <table>
                            <thead>
                              <tr>
                                <th>评价</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr class="pingjia_tr" id="${value.orderId}"></tr>
                            </tbody>
                          </table>
                        </div>
                        <div class="delete_wish_close" style="top: 5px;
                        left: 1268px;">
                        <div class="delete_wish_close_mask" data-id="${value.orderId}"></div>
                    <button aria-label="删除「哈哈哈」（未共享）" type="button" class="l1ovpqvx cwgqky9 dir dir-ltr"><span
                            class="i13tpwjr dir dir-ltr"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"
                                aria-hidden="true" role="presentation" focusable="false"
                                style="display: block; height: 12px; width: 12px; fill: currentcolor;">
                                <path
                                    d="m14.3.3 1.4 1.4L9.43 8l6.29 6.3-1.42 1.4L8 9.43 1.7 15.7.3 14.29 6.57 8 .3 1.7 1.71.3 8 6.57z">
                                </path>
                            </svg></span></button>
                </div>
                      </div>`;

                        $('.order_thing_main1').insertAdjacentHTML('beforeend', str);

                        const reviewResponse = await instance.get(`/review/order/${value.orderId}`, {
                            headers: {
                                'Authorization': window.localStorage.getItem('token'),
                                'Content-Type': 'application/json',
                            }
                        });
                        const reviewarr = reviewResponse.data.data;

                        let reviewStr = `${value.isReview ? `
                        <td class="order_content">
                          <div>
                            ${reviewarr.content}
                          </div>
                        </td>` : `
                        <td class="order_content">
                          <div>
                            无
                          </div>
                        </td>`}`;

                        document.getElementById(`${value.orderId}`).insertAdjacentHTML('beforeend', reviewStr);

                        if (value.isReview == 0) {
                            num1++;
                        } else {
                            num2++;
                        }

                        let now = new Date();  // 当前时间
                        let targetDate = new Date(value.endTime);
                        let reserveDate = new Date(value.startTime);

                        if (now > targetDate) {
                            num3++;
                            outarr.push(value.orderId)
                        } else if (now < reserveDate) {
                            num4++;
                            notarr.push(value.orderId)
                        } else if (now >= reserveDate && now <= targetDate) {
                            num5++;
                            livingarr.push(value.orderId)
                        }
                    }

                    return {
                        num1: num1,
                        num2: num2,
                        num3: num3,
                        num4: num4,
                        num5: num5
                    };
                }

                (async function () {
                    const { num1, num2, num3, num4, num5 } = await fetchData();
                    $('.remain_evaluated').innerHTML = num1;
                    $('.rated').innerHTML = num2;
                    $('.check_out_house').innerHTML = num3;
                    $('.not_start').innerHTML = num4;
                    $('.living').innerHTML = num5;
                })();

            } else {
                $('.order_box').style.display = 'flex';
            }


        })
    }



    //取消订单
    $('.order_thing_main1').addEventListener('click', function (event) {
        const targetElement = event.target;


        if (targetElement.classList.contains('delete_wish_close_mask')) {
            let orderid = targetElement.getAttribute('data-id');
            console.log(orderid);

            $('.pop_mask').style.display = 'block';
            $('.check_out').style.display = 'block';
            $('.check_out').classList.add('visible');


            $('.check_out_ok').onclick = function () {
                instance({
                    url: `/order/${orderid}`,
                    method: 'DELETE',
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                }).then(response => {
                    console.log(response);
                    base.tooltipBox('', '取消订单成功!', '1');
                    setTimeout(function () {
                        location.reload(true);
                    }, 500);


                }).catch(error => {
                    console.error(error)
                })
            }

        }
    });




    //点击评论
    $('.order_thing_main2').addEventListener('click', function (event) {
        const targetElement = event.target;
        let orderid = targetElement.id;
        console.log(orderid);

        if (targetElement.classList.contains('dianji')) {

            $('.pop_mask').style.display = 'block';
            $('.pop_review').style.display = 'flex';
            $('.pop_review').classList.add('slidedownup');

            $('.pop_publish').onclick = base.debounce(function () {
                if ($('.textbox textarea').value && $('input[name="pop_star"]:checked')) {
                    instance.post(`/review/${orderid}`, {
                        content: base.SaferHTML`${$('.textbox textarea').value}`,
                        star: $('input[name="pop_star"]:checked').id
                    }, {
                        headers: {
                            'Authorization': window.localStorage.getItem('token'),
                            'Content-Type': 'application/json',
                        }
                    }).then(response => {
                        $('.pop_close').click();
                        console.log(targetElement.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);

                        targetElement.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.remove();
                        $('.remain_evaluated').innerHTML--;
                        $('.rated').innerHTML++;

                        base.tooltipBox('', '评价成功!', '1');
                    }).catch(error => {
                        console.error(error)
                    })

                } else {
                    base.tooltipBox('', '请完成所有评价内容!', '0');
                }
            })


        }
    });



    //修改评论
    let reviewId;
    $('.order_thing_main3').addEventListener('click', function (event) {
        const targetElement = event.target;

        if (targetElement.classList.contains('change')) {
            let orderid = targetElement.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute('data-order');

            instance.get(`/review/order/${orderid}`, {
                headers: {
                    'Authorization': window.localStorage.getItem('token'),
                    'Content-Type': 'application/json',
                }
            }).then(response => {
                console.log(response.data.data);
                reviewId = response.data.data.reviewId;
                $('.pop_mask').style.display = 'block';
                $('.pop_review').style.display = 'flex';
                $('.pop_review').classList.add('slidedownup');
            })

            $('.pop_publish').onclick = base.debounce(function () {
                if ($('.textbox textarea').value && $('input[name="pop_star"]:checked')) {
                    instance.post(`/review/update/${reviewId}`, {
                        content: base.SaferHTML`${$('.textbox textarea').value}`,
                        star: $('input[name="pop_star"]:checked').id
                    }, {
                        headers: {
                            'Authorization': window.localStorage.getItem('token'),
                            'Content-Type': 'application/json',
                        }
                    }).then(response => {

                        base.tooltipBox('', '修改成功!', '1');
                        $('.pop_close').click();

                    }).catch(error => {
                        console.error(error)
                    })

                } else {
                    base.tooltipBox('', '请输入修改内容!', '0');
                }
            })


        }

        if (targetElement.classList.contains('delete')) {
            let orderid = targetElement.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute('data-order');

            instance.get(`/review/order/${orderid}`, {
                headers: {
                    'Authorization': window.localStorage.getItem('token'),
                    'Content-Type': 'application/json',
                }
            }).then(response => {
                console.log(response.data.data);
                reviewId = response.data.data.reviewId;
                $('.pop_mask').style.display = 'block';
                $('.delete_wish').style.display = 'block';
                $('.delete_wish').classList.add('visible');

            })

            $('.delete_wish_b_r').onclick = base.debounce(function () {
                instance({
                    url: `/review/${reviewId}`,
                    method: 'DELETE',
                    headers: {
                        'Authorization': window.localStorage.getItem('token'),
                        'Content-Type': 'application/json',
                    }
                }).then(response => {
                    console.log(response);
                    $('.pop_mask').style.display = 'none';
                    $('.delete_wish').style.display = 'none';
                    console.log(targetElement.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);
                    targetElement.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.remove();
                    $('.remain_evaluated').innerHTML++;
                    $('.rated').innerHTML--;

                    base.tooltipBox('', '删除成功!', '1');

                    setTimeout(function () {
                        location.reload(true);
                    }, 500);

                }).catch(error => {
                    console.error(error)
                })
            })


        }
    });




    function close(obj1, obj2) {
        $(`${obj1}`).addEventListener('click', function () {


            $(`${obj2}`).classList.add('reverse-animation');

            // 等待动画结束后移除.visible和.reverse-animation类名
            setTimeout(function () {
                $(`${obj2}`).classList.remove('visible', 'reverse-animation');
                $(`${obj2}`).style.display = 'none';
                $('.pop_mask').style.display = 'none';
            }, 500);
        })
    }


    close('.pop_close', '.pop_review');


    //关闭删除页面
    close('.delete_wish_close', '.delete_wish');
    close('.delete_wish_b_l', '.delete_wish');

    //关闭取消页面
    close('.check_out_close', '.check_out');
    close('.check_out_no', '.check_out');

    $('.pop_mask').addEventListener('click', function () {
        $('.pop_mask').style.display = 'none';
        if ($('.pop_review').style.display == 'flex') {
            $('.pop_review').style.display = 'none';
        } else if ($('.delete_wish').style.display == 'block') {
            $('.delete_wish').style.display = 'none';
        } else if ($('.check_out').style.display == 'block') {
            $('.check_out').style.display = 'none';
        }
    })



    // tab切换
    $$('.order_ul li').forEach(function (value, index, array) {
        $$('.order_ul li')[index].addEventListener('click', function () {
            $$('.order_ul li').forEach(function (value, index1, array) {
                $$('.order_ul li')[index1].classList.remove('order_current');
            })
            $$('.order_ul li')[index].classList.add('order_current');
        })
    })



    //tab栏部分
    function tab(num) {
        return new Promise((resolve, reject) => {
            $$('.order_thing_main').forEach(function (value, index, array) {
                $$('.order_thing_main')[index].style.display = 'none';
            })
            $(`.order_thing_main${num}`).style.display = 'block';

            $$(`.order_thing_main${num} .order_thing`).forEach(function (value, index, array) {
                value.remove();
            })

            resolve();
        });

    }

    //全部
    $('.order_all_main').addEventListener('click', function () {
        tab(1).then(orderall);
    })


    //待评价
    $('.remain_evaluate').addEventListener('click', function () {
        tab(2);
        instance.get('/order/user', {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            orderarr = response.data.data;
            console.log(orderarr);


            if (orderarr != null) {
                let changenum = 0;
                orderarr.forEach(function (value, index, array) {
                    if (orderarr[index].isReview == 0) {
                        changenum++;
                        instance.get(`/home/detail/${orderarr[index].homeId}`, {
                            headers: {
                                'Authorization': window.localStorage.getItem('token'),
                                'Content-Type': 'application/json',
                            }
                        }).then(response => {
                            let detailarr = response.data.data;
                            let str = `<div class="order_thing" data-order="${orderarr[index].isReview}">
                        <div>订单 <span>${index + 1}</span> </div>
                        <div>
                        <table>
                        <thead>
                        <tr>
                            <th>房源信息</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>标题</td>
                                <td>${detailarr.title}</td>
                            </tr>
                            <tr>
                                <td>介绍</td>
                                <td>${detailarr.introduce}</td>
                            </tr>
                            <tr>
                                <td>最大入住人数</td>
                                <td>${detailarr.tenant}</td>
                            </tr>
                            <tr>
                                <td>价格</td>
                                <td>${detailarr.price}</td>
                            </tr>
                            <tr>
                                <td>评分</td>
                                <td>${detailarr.star}</td>
                            </tr>
                            <tr>
                                <td>房源类型</td>
                                <td>${detailarr.houseType.name}</td>
                            </tr>
                            </tbody>
                            </table>
                            <table>
                            <thead>
                                    <tr>
                                        <th>订单信息</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>开始时间</td>
                                        <td>${orderarr[index].startTime}</td>
                                    </tr>
                                    <tr>
                                        <td>结束时间</td>
                                        <td>${orderarr[index].endTime}</td>
                                    </tr>
                                    <tr>
                                        <td>订单号</td>
                                        <td>${orderarr[index].orderId}</td>
                                    </tr>
                                </tbody>
                                </table>
                                <table>
                            <thead>
                                <tr>
                                    <th>评价</th>
                                </tr>
                            </thead>
                            <tbody>
                            <tr class="pingjia_tr">
                            <td class="order_ping">
                                            <div class="dianji" id="${orderarr[index].orderId}">
                                                点击评价
                                            </div>
                                        </td>
                            </tr>
                            </tbody>
                            </table>
                                    </div>
                                    </div>`

                            $('.order_thing_main2').insertAdjacentHTML('beforeend', str);
                        })


                    }

                })
                if (changenum == 0) {
                    $('.order_box').style.display = 'flex';
                }


            }

        })
    })

    //已评价
    $('.rated_box').addEventListener('click', function () {
        tab(3);
        instance.get('/order/user', {
            headers: {
                'Authorization': window.localStorage.getItem('token'),
                'Content-Type': 'application/json',
            }
        }).then(response => {
            orderarr = response.data.data;
            console.log(orderarr);


            if (orderarr != null) {
                let changenum = 0;
                orderarr.forEach(function (value, index, array) {
                    if (orderarr[index].isReview == 1) {
                        changenum++;
                        instance.get(`/home/detail/${orderarr[index].homeId}`, {
                            headers: {
                                'Authorization': window.localStorage.getItem('token'),
                                'Content-Type': 'application/json',
                            }
                        }).then(response => {
                            let detailarr = response.data.data;
                            let str = `<div class="order_thing" data-order="${orderarr[index].orderId}">
                        <div>订单 <span>${index + 1}</span> </div>
                        <div>
                        <table>
                        <thead>
                        <tr>
                            <th>房源信息</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>标题</td>
                                <td>${detailarr.title}</td>
                            </tr>
                            <tr>
                                <td>介绍</td>
                                <td>${detailarr.introduce}</td>
                            </tr>
                            <tr>
                                <td>最大入住人数</td>
                                <td>${detailarr.tenant}</td>
                            </tr>
                            <tr>
                                <td>价格</td>
                                <td>${detailarr.price}</td>
                            </tr>
                            <tr>
                                <td>评分</td>
                                <td>${detailarr.star}</td>
                            </tr>
                            <tr>
                                <td>房源类型</td>
                                <td>${detailarr.houseType.name}</td>
                            </tr>
                            </tbody>
                            </table>
                            <table>
                            <thead>
                                    <tr>
                                        <th>订单信息</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>开始时间</td>
                                        <td>${orderarr[index].startTime}</td>
                                    </tr>
                                    <tr>
                                        <td>结束时间</td>
                                        <td>${orderarr[index].endTime}</td>
                                    </tr>
                                    <tr>
                                        <td>订单号</td>
                                        <td>${orderarr[index].orderId}</td>
                                    </tr>
                                </tbody>
                                </table>
                                <table>
                            <thead>
                                <tr>
                                    <th>评价</th>
                                </tr>
                            </thead>
                            <tbody>
                            <tr class="pingjia_tr">
                            <td class="order_ping">
                            <div class="change">
                            修改评价
                            </div>
                            <div class="delete">
                                删除评价
                            </div>
                            </td>
                            </tr>
                            </tbody>
                            </table>
                                    </div>
                                    </div>`

                            $('.order_thing_main3').insertAdjacentHTML('beforeend', str);

                        })

                    }


                })
                if (changenum == 0) {
                    $('.order_box').style.display = 'flex';
                }

            }

        })
    })



    function timethree(arr) {
        let num = 0;
        $('.order_box').style.display = 'none';
        $$('.order_thing_main').forEach(function (value, index, array) {
            $$('.order_thing_main')[index].style.display = 'none';
        })
        $('.order_thing_main1').style.display = 'block';
        $$('.order_thing_main1 .order_thing').forEach(function (value, index, array) {

            if (arr.includes(parseInt(value.getAttribute('data-orderid')))) {
                value.style.display = 'block';
            } else {
                value.style.display = 'none';
                num++;
            }

            if (num == $$('.order_thing_main1 .order_thing').length) {
                $('.order_box').style.display = 'flex';
            }
        })
    }

    $('.check_out_house_box').addEventListener('click', function () {
        timethree(outarr);
    })
    $('.living_box').addEventListener('click', function () {
        timethree(livingarr);
    })
    $('.not_start_box').addEventListener('click', function () {
        timethree(notarr);
    })

})